/**
 * listen to the port and create thread to handle the http request
 */

#include "common.h"
#include "http_deal.h"
#include "socket_thread_map.h"

#define QLEN 10
#define LISTEN_PORT 8080
#ifndef  HOST_NAME_MAX
#endif

#define  HOST_NAME_MAX 256x

//global thread socket map
extern socket_thread_map *socket_thread_table;

int init_server(int type,const struct sockaddr*addr,socklen_t alen,int qlen)
{
    int fd,err = 0;

    if((fd = socket(addr->sa_family,type,0)) < 0){
        return FAILURE;
    }
    printf("get socket success\n");

    if(bind(fd,addr,alen) <0){
        err = errno;
        goto errout;
    }
    printf("bind success\n");
    if(type == SOCK_STREAM || type == SOCK_SEQPACKET){
        if(listen(fd,qlen) < 0){
            err = errno;
            goto errout;
        }
        printf("listen success\n");
    }
    return fd;

    errout:
        close(fd);
        errno = err;
        return FAILURE;
}

void serve(int sockfd){

    int clfd,err;
    pthread_t pthreadT;
    while (1){
        clfd = accept(sockfd,NULL,NULL);
        if (clfd < 0){
            syslog(LOG_ERR,"myhttpserver accept error: %s",strerror(errno));
            exit(1);
        }

        err = pthread_create(&pthreadT,NULL,http_deal,(void*)&clfd);
        if(err != SUCCESS){
            printf("create http deal thread failured for errno : %d\n",err);
            return;
        }

    }
}

int main(int argc,char * argv[]) {

    //setting listen address
    struct sockaddr_in *addr = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
    addr->sin_family = AF_INET;
    addr->sin_port = htons(LISTEN_PORT);
    addr->sin_addr.s_addr = INADDR_ANY;
    memset(&(addr->sin_zero),'\0',sizeof(addr->sin_zero));

    int sockFileId;
    if((sockFileId = init_server(SOCK_STREAM,(struct sockaddr*)addr,sizeof(struct sockaddr_in),QLEN) ) >= 0){
        serve(sockFileId);
        exit(0);
    }

    exit(errno);
}